package com.tqz.rc.server.cluster;

import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

/**
 * <p>服务端每个节点的数据
 *
 * @author tianqingzhao
 * @since 2021/9/24 10:23
 */
public class Member {

    private String ip;

    private int port = -1;

    private String address;

    private volatile NodeState state = NodeState.UP;

    private Map<String, Object> extendInfo = Collections.synchronizedMap(new TreeMap<>());

    public static MemberBuilder builder() {
        return new MemberBuilder();
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public NodeState getState() {
        return state;
    }

    public void setState(NodeState state) {
        this.state = state;
    }

    public Map<String, Object> getExtendInfo() {
        return extendInfo;
    }

    public void setExtendInfo(Map<String, Object> extendInfo) {
        this.extendInfo = extendInfo;
    }

    public static final class MemberBuilder {

        private String ip;

        private int port;

        private NodeState state;

        private Map<String, String> extendInfo = Collections.synchronizedMap(new TreeMap<>());

        private MemberBuilder() {
        }

        public MemberBuilder ip(String ip) {
            this.ip = ip;
            return this;
        }

        public MemberBuilder port(int port) {
            this.port = port;
            return this;
        }

        public MemberBuilder state(NodeState state) {
            this.state = state;
            return this;
        }

        public MemberBuilder extendInfo(Map<String, String> extendInfo) {
            this.extendInfo.putAll(extendInfo);
            return this;
        }

        /**
         * build Member.
         *
         * @return {@link Member}
         */
        public Member build() {
            Member serverNode = new Member();
            if (Objects.nonNull(this.extendInfo)) {
                serverNode.extendInfo.putAll(this.extendInfo);
            }
            serverNode.state = this.state;
            serverNode.ip = this.ip;
            serverNode.port = this.port;
            serverNode.address = this.ip + ":" + this.port;
            return serverNode;
        }
    }
}
